import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { MapPin, Navigation, RefreshCw } from 'lucide-react'

const API_BASE_URL = 'http://localhost:5000/api'

export default function MapView({ circle, user }) {
  const [locations, setLocations] = useState([])
  const [userLocation, setUserLocation] = useState(null)
  const [selectedUser, setSelectedUser] = useState(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    fetchLocations()
    // 模拟获取用户当前位置
    getCurrentLocation()
    
    // 每30秒刷新一次位置
    const interval = setInterval(fetchLocations, 30000)
    return () => clearInterval(interval)
  }, [circle.id])

  const fetchLocations = async () => {
    try {
      const response = await fetch(
        `${API_BASE_URL}/locations/circles/${circle.id}/locations?user_id=${user.id}`
      )
      const data = await response.json()
      
      if (response.ok) {
        setLocations(data)
      }
    } catch (err) {
      console.error('获取位置失败:', err)
    }
  }

  const getCurrentLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords
          setUserLocation({ latitude, longitude })
          // 上传位置到服务器
          updateLocation(latitude, longitude, position.coords.accuracy)
        },
        (error) => {
          console.error('获取位置失败:', error)
          // 使用模拟位置（丽江古城）
          const mockLocation = { latitude: 26.8721, longitude: 100.2319 }
          setUserLocation(mockLocation)
          updateLocation(mockLocation.latitude, mockLocation.longitude, 10)
        }
      )
    } else {
      // 浏览器不支持地理位置，使用模拟位置
      const mockLocation = { latitude: 26.8721, longitude: 100.2319 }
      setUserLocation(mockLocation)
      updateLocation(mockLocation.latitude, mockLocation.longitude, 10)
    }
  }

  const updateLocation = async (latitude, longitude, accuracy) => {
    try {
      await fetch(`${API_BASE_URL}/locations/locations`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          user_id: user.id,
          circle_id: circle.id,
          latitude,
          longitude,
          accuracy,
        }),
      })
    } catch (err) {
      console.error('上传位置失败:', err)
    }
  }

  const handleRefresh = () => {
    setLoading(true)
    getCurrentLocation()
    fetchLocations()
    setTimeout(() => setLoading(false), 1000)
  }

  const formatTime = (timestamp) => {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = Math.floor((now - date) / 1000 / 60) // 分钟差
    
    if (diff < 1) return '刚刚'
    if (diff < 60) return `${diff}分钟前`
    if (diff < 1440) return `${Math.floor(diff / 60)}小时前`
    return date.toLocaleDateString()
  }

  return (
    <div className="h-full flex flex-col">
      {/* 模拟地图区域 */}
      <div className="flex-1 relative bg-gradient-to-br from-green-100 to-blue-100 overflow-hidden">
        {/* 地图背景 */}
        <div className="absolute inset-0 opacity-20">
          <svg viewBox="0 0 400 300" className="w-full h-full">
            {/* 模拟山脉 */}
            <path
              d="M0,200 Q100,150 200,180 T400,160 L400,300 L0,300 Z"
              fill="currentColor"
              className="text-green-300"
            />
            <path
              d="M0,220 Q150,170 300,200 T400,180 L400,300 L0,300 Z"
              fill="currentColor"
              className="text-green-200"
            />
            {/* 模拟河流 */}
            <path
              d="M0,250 Q100,240 200,260 T400,250"
              stroke="currentColor"
              strokeWidth="8"
              fill="none"
              className="text-blue-300"
            />
          </svg>
        </div>

        {/* 用户位置标记 */}
        {locations.map((location, index) => (
          <div
            key={location.user.id}
            className="absolute transform -translate-x-1/2 -translate-y-1/2 cursor-pointer"
            style={{
              left: `${20 + (index * 15) % 60}%`,
              top: `${30 + (index * 20) % 40}%`,
            }}
            onClick={() => setSelectedUser(location)}
          >
            <div className="relative">
              <Avatar className="w-12 h-12 border-4 border-white shadow-lg">
                <AvatarImage src={location.user.avatar_url} />
                <AvatarFallback className="bg-walker-orange text-white">
                  {location.user.nickname?.charAt(0) || '用'}
                </AvatarFallback>
              </Avatar>
              <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white"></div>
            </div>
          </div>
        ))}

        {/* 刷新按钮 */}
        <div className="absolute top-4 right-4">
          <Button
            size="sm"
            variant="secondary"
            onClick={handleRefresh}
            disabled={loading}
            className="bg-white/90 hover:bg-white"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </Button>
        </div>

        {/* 定位按钮 */}
        <div className="absolute bottom-4 right-4">
          <Button
            size="sm"
            onClick={getCurrentLocation}
            className="bg-walker-blue hover:bg-walker-blue/90"
          >
            <Navigation className="w-4 h-4" />
          </Button>
        </div>
      </div>

      {/* 用户信息弹窗 */}
      {selectedUser && (
        <Card className="absolute bottom-20 left-4 right-4 z-10">
          <CardContent className="p-4">
            <div className="flex items-center space-x-3">
              <Avatar className="w-12 h-12">
                <AvatarImage src={selectedUser.user.avatar_url} />
                <AvatarFallback className="bg-walker-orange text-white">
                  {selectedUser.user.nickname?.charAt(0) || '用'}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1">
                <h3 className="font-semibold">{selectedUser.user.nickname}</h3>
                <p className="text-sm text-gray-600">
                  {formatTime(selectedUser.timestamp)}更新位置
                </p>
                <div className="flex items-center space-x-1 text-xs text-gray-500">
                  <MapPin className="w-3 h-3" />
                  <span>
                    {selectedUser.latitude.toFixed(4)}, {selectedUser.longitude.toFixed(4)}
                  </span>
                </div>
              </div>
              <Button
                size="sm"
                variant="outline"
                onClick={() => setSelectedUser(null)}
              >
                关闭
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 底部状态栏 */}
      <div className="bg-white border-t p-3">
        <div className="flex items-center justify-between text-sm text-gray-600">
          <div className="flex items-center space-x-1">
            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
            <span>{locations.length}位成员在线</span>
          </div>
          <div className="flex items-center space-x-1">
            <MapPin className="w-4 h-4" />
            <span>实时位置共享</span>
          </div>
        </div>
      </div>
    </div>
  )
}

